import { message } from "antd";
import fetch from "isomorphic-fetch";
import { browserHistory } from "react-router";

export default function (url, body = {}) {
  const token = localStorage.getItem("token");
  if (!token && !(url.indexOf('/log') !== -1 || url.indexOf('/adminlog') !== -1)) {
    message.warning("请登录");
    browserHistory.push("/login");
    return Promise.reject('登陆状态过期了');
  } else {
    const content = JSON.stringify(body);
    return fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": content.length.toString(),
        token
      },
      body: content
    }).then(res => {
      if (res.status === 401 && res.statusText === "Unauthorized") {
        message.warning("登陆状态已过期，请重新登录");
        browserHistory.push("/login");
        return Promise.reject(res);
      } else {
        if (res.ok) {
          return res.json();
        } else {
          // res.json().then(err=>message.error(err.message));
          return Promise.reject(res);
        }
      }
    }).then(res => {
      const { code, data, msg } = res;
      if (code === 1) {
        message.error(msg || '服务器开小差');
      } else {
        return data;
      }
    });
  }
}
